var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var _limitMenu = system.MENULIMIT.BUY24;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'buy/report/type_level_enter';
var _height = $(parent).height()-328,_width = $(parent).width()-192;
var api = frameElement.api;
if(api){
	_height = $(defaultPage).height()-348,_width = $(defaultPage).width()-222;
}
var handle = {
	queryChildType:function(Code){
		var params = {};
		params.supply_name = $("#supply_name").val();
		params.et_supply_code = $("#et_supply_code").val();
		params.bd_name = $("#bd_name").val();
		params.bd_code = $("#bd_code").val();
		params.pd_season = $("#pd_season").val();
		params.year = $("#year").val();
        $.dialog({
            id:'',
            title:false,
            data:params,
            max: false,
            min: false,
            fixed:false,
            drag:false,
            resize:false,
            lock:false,
            content:'url:'+config.BASEPATH+'buy/report/to_type_level_enter/'+Code,
            close:function(){
            }
        }).max();
    },
	formatData :function(val, opt, row){
		if($.trim(val) == ""){
			return "";
		}
		if(row.tp_code == "合计"){
			return val;
		}
		if(row.project == '数量'){
			return val;
		}else if(row.project == '金额'){
			return PriceLimit.formatMoney(val);
		}
		return '';
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		if("0" == $("#tp_upcode").val()){
			$("#btn_close").hide();
		}
		this.initParams();
		Public.buildSeasonCombo("span_pd_season", "pd_season");
		Public.buildYearBeforeCombo("span_year", "year");
	},
	initParams:function(){
		if(api == undefined){
			return;
		}
		var params = api.data;
		$("#et_supply_code").val($.trim(params.et_supply_code));
		$("#supply_name").val($.trim(params.supply_name));
		$("#bd_name").val($.trim(params.bd_name));
		$("#bd_code").val($.trim(params.bd_code));
		$("#pd_season").val($.trim(params.pd_season));
		$("#year").val($.trim(params.year));
	},
	gridTotal:function(){
    	var grid = $('#grid');
		var footerData = {tp_code:'合计'};
		var ids = $("#grid").getDataIDs();
		var amountTotal = {};
		var moneyTotal = {};
		for (var i = 1; i <= 12; i++) {
			amountTotal[i+""] = 0;
			moneyTotal[i+""] = 0;
		}
		amountTotal["total"] = 0;
		moneyTotal["total"] = 0;
		for (var i = 0; i < ids.length; i++) {
			var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			if(rowData.project == '数量'){
				for(var key in amountTotal){
					if($.trim(rowData[key]) != ""){
						amountTotal[key] = amountTotal[key] + parseInt(rowData[key]);
					}
				}
			}else if(rowData.project == '金额'){
				for(var key in moneyTotal){
					if($.trim(rowData[key]) != ""){
						moneyTotal[key] = moneyTotal[key] + parseFloat(rowData[key]);
					}
				}
			}
		}
		for(var key in amountTotal){
			footerData[key] = amountTotal[key]+'<br>'+moneyTotal[key].toFixed(2);
		}
		grid.footerData('set',footerData);
    },
	initGrid:function(){
		$("#grid").jqGrid('GridUnload');
		var colModel = [
	    	{label:'类别编号',name: 'tp_code',index:'tp_code',width:80,
	    		cellattr: function(rowId, tv, rawObject, cm, rdata) {return 'id=\'tp_code' + rowId + "\'";}},
	    	{label:'类别名称',name: 'tp_name',index:'tp_name',width:100,
	    		cellattr: function(rowId, tv, rawObject, cm, rdata) {return 'id=\'tp_name' + rowId + "\'";}},
	    	{label:'',name: 'child_type',index:'child_type',width:100,hidden:true},
	    	{label:'',name: 'tp_code_hid',index:'tp_code_hid',width:100,hidden:true},
	    	{label:'项目',name: 'project',index:'project',width:100}
	    ];
		for (var i = 1; i <= 12; i++) {
			colModel.push({label:i+"月份",name: i+"",index:'',width: 80,sortable:false,align:'right',formatter: handle.formatData});
		}
		colModel = colModel.concat([
			{label:'小计',name: 'total',index: 'total',width:70,align:"right",formatter: handle.formatData}
		]);
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:-1,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			scroll: 1,//是否滚动
			jsonReader: {
				root: 'data',
				repeatitems : false,
				id: 'id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
				THISPAGE.Merger2('tp_code');
				THISPAGE.Merger2('tp_name');
			},
			loadError: function(xhr, status, error){		
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				var tp_upcode = $("#tp_upcode").val();
				var rowData = $("#grid").jqGrid("getRowData", rowid);
				if(tp_upcode == rowData.tp_code_hid){
					Public.tips({type: 2, content : '当前页面已经是该类别的子级数据！'});
					return;
				}
				if(rowData.child_type == "" || rowData.child_type == rowData.tp_code_hid){
					Public.tips({type: 2, content : '无子类别或子类别无数据！'});
					return;
				}
				handle.queryChildType(rowData.tp_code_hid);
			}
	    });
	},
	Merger2:function(CellName){
    	var ids = $("#grid").getDataIDs();
        var length = ids.length;
        for (var i = 0; i < length; i++) {
            var before = $("#grid").jqGrid('getRowData', ids[i]);
            if(i%2 == 0){
            	$("#" + CellName + "" + ids[i] + "").attr("rowspan", 2);
            }else{
            	$("#grid").setCell(ids[i], CellName, '', { display: 'none' });
            }
        }
    },
	buildParams : function(){
		var params = '';
		params += 'tp_upcode='+$("#tp_upcode").val();
		params += '&bd_code='+$("#bd_code").val();
		params += '&pd_season='+$("#pd_season").val();
		params += '&year='+$("#year").val();
		params += '&et_supply_code='+$("#et_supply_code").val();
		return params;
	},
	reset:function(){
		$("#et_supply_code").val("");
		$("#supply_name").val("");
		$("#bd_name").val("");
		$("#bd_code").val("");
		$("#span_pd_season").getCombo().selectByValue("");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.initGrid();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.initGrid();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
	}
}
THISPAGE.init();